#include "thread.h"
#include <unistd.h>
#include <pthread.h>
#include "latch.h"

using namespace tiny_muduo;

namespace CurrentThread{
    thread_local int t_cachedTid=0; 
    thread_local char t_formattedTid[32];
    thread_local int t_formattedTidLength;

    void CacheTid(){
        if(t_cachedTid==0){
            t_cachedTid=::gettid();
            t_formattedTidLength=snprintf(t_formattedTid,sizeof(t_formattedTid),"%5d",t_cachedTid);
        }
    }
}

static void* ThreadRun(void* arg){
    ThreadData* ptr=static_cast<ThreadData*>(arg);
    ptr->RunOneFunc();
    delete ptr;
    return nullptr;
}

Thread::Thread(const ThreadFunc& func)
    :pthread_id_(-1),
     func_(func),
     latch_(1){
}

Thread::~Thread(){
    ::pthread_detach(pthread_id_);
}

void Thread::StartThread(){
    ThreadData* ptr=new ThreadData(func_,&latch_);
    ::pthread_create(&pthread_id_,nullptr,ThreadRun,ptr);
    latch_.Wait();
}